# gradio_app.py

# --- 1. 环境修复补丁 (保持不变) ---
import llama_index.core
from llama_index.core.instrumentation.dispatcher import Dispatcher
from llama_index.core.callbacks import CallbackManager

class DummyDispatcher(Dispatcher):
    def dispatch(self, event) -> None:
        pass

llama_index.core.Settings.dispatcher = DummyDispatcher()
llama_index.core.Settings.callback_manager = CallbackManager([])
print("✅ [Gradio] 环境修复补丁已应用。")

# --- 2. 导入必要的库 ---
import gradio as gr
import asyncio
from fastapi import FastAPI # 导入 FastAPI
import uvicorn # 导入 Uvicorn

# --- 全局变量 ---
query_engine = None

# --- 3. Gradio 处理函数 (保持不变) ---
async def get_streaming_response(user_question: str, chat_history: list):
    if query_engine is None:
        yield chat_history + [(user_question, "错误：查询引擎仍在加载中或初始化失败。")]
        return
    response_stream = await query_engine.aquery(user_question)
    chat_history.append((user_question, ""))
    full_response = ""
    async for chunk in response_stream.async_response_gen():
        full_response += chunk
        chat_history[-1] = (user_question, full_response)
        yield chat_history

# --- 4. Gradio UI 定义 (保持不变) ---
with gr.Blocks(theme=gr.themes.Soft(), title="企业级 RAG 系统") as demo:
    gr.Markdown("# 企业级 RAG 系统 - Gradio 界面")
    chatbot = gr.Chatbot(label="对话窗口", height=650)
    msg_textbox = gr.Textbox(label="您的问题", placeholder="在这里输入您的问题...", scale=7)
    clear_button = gr.Button("🗑️ 清除对话", scale=1)

    msg_textbox.submit(
        fn=get_streaming_response,
        inputs=[msg_textbox, chatbot],
        outputs=[chatbot]
    )
    msg_textbox.submit(lambda: "", None, msg_textbox)
    clear_button.click(lambda: None, None, chatbot, queue=False)

# --- 5. FastAPI 应用和生命周期事件 ---
# 创建一个 FastAPI 实例
app = FastAPI()

@app.on_event("startup")
async def startup_event():
    """
    在 FastAPI 服务器启动时执行。
    这是加载重量级模型最安全、最推荐的地方。
    """
    global query_engine
    print("🚀 [FastAPI Startup] 开始构建查询引擎...")
    from fusion_retriever.core.engine import build_query_engine # 注意这里我们导入函数
    query_engine = build_query_engine() # 直接调用构建函数
    print("✅ [FastAPI Startup] 查询引擎已成功构建。")

# --- 关键步骤：将 Gradio 应用挂载到 FastAPI ---
# 这会将 Gradio 的所有路由都添加到 FastAPI 应用中，根路径为 "/"
app = gr.mount_gradio_app(app, demo, path="/")


# --- 6. 主执行块 ---
# 使用 Uvicorn 来运行我们的 FastAPI 应用
if __name__ == "__main__":
    print("🚀 [Main] 正在使用 Uvicorn 启动 FastAPI 和 Gradio...")
    uvicorn.run(app, host="127.0.0.1", port=7860)